/*
 * @Description: 订单校验规则页面
 * @Version: 1.0
 * @Autor: c-jack.qian
 * @Date: 2020-10-21 17:30:52
 * @LastEditors: c-jack.qian
 * @LastEditTime: 2021-03-30 16:30:58
 */

import React, { useMemo, useRef } from 'react';
import { PageHeaderWrapper } from 'hzero-boot/lib/components/Page';
import {
  Button,
  DataSet,
  Form,
  Modal,
  notification,
  NumberField,
  Select,
  SelectBox,
  Table,
} from 'choerodon-ui/pro';
import { ButtonColor, FuncType } from 'choerodon-ui/pro/lib/button/enum';
import { useDataSet, useDataSetEvent } from 'hzero-front/lib/utils/hooks';
import { DataSetProps } from 'choerodon-ui/pro/lib/data-set/DataSet';
import request from 'utils/request';
import { ColumnLock, TableColumnTooltip } from 'choerodon-ui/pro/lib/table/enum';
import intl from 'utils/intl';
import { Popconfirm } from 'choerodon-ui';
import { DataSetSelection, FieldType } from 'choerodon-ui/pro/lib/data-set/enum';
import { renderSort, addEnterCallBack } from '../../utils/utilsFun';
// import commonConfigStore from '@common/config/commonConfig';
import { orderCheckRuleListDS, createDS } from '../../stores/orderCheckRuleListDS';
import CustomizeTableSearch from '@common/components/CustomizeTableSearch';
import formatterCollections from 'utils/intl/formatterCollections';

const detailModalKey = Modal.key();
notification.config({
  duration: 3,
  placement: 'bottomRight',
});


const ClassPage: React.FC = () => {
  const tableDS = useDataSet(() => new DataSet(orderCheckRuleListDS() as DataSetProps));
  const createListDS = useDataSet(() => new DataSet(createDS() as DataSetProps));
  const pageRef = useRef(null);

  // 添加按回车查询事件
  addEnterCallBack(tableDS, pageRef);

  useDataSetEvent(createListDS, 'update', ({ dataSet, name }) => {
    if (name === 'checkRuleCode') {
      updateCheckRuleCode(dataSet);
    }
  });

  useDataSetEvent(tableDS, 'update', ({ dataSet, name }) => {
    if (name === 'checkRuleCode') {
      updateCheckRuleCode(dataSet);
    }
  });

  const updateCheckRuleCode = dataSet => {
    const currentRecord = dataSet.current;
    if (currentRecord.get('beanId')) {
      currentRecord.set('beanId', null);
    }
    const parentValue = currentRecord.get('checkRuleCode');
    reqBeanIdOption(parentValue, dataSet);
  };

  //请求BeanId值集数据 若该父集校验规则的值下仅有一个子值集值，则默认带出
  const reqBeanIdOption = (parentValue, dataSet) => {
    request('/hpfm/v1/0/lovs/data', {
      method: 'get',
      query: {
        lovCode: 'DJIOM.RULE_BEAN_ID',
      },
    }).then(res => {
      // 通过父集校验规则过滤数据
      const optionData =
        res.filter(item => {
          return item.parentValue === parentValue;
        }) || [];

      dataSet.addField('beanId', {
        name: 'beanId',
        type: FieldType.string,
        label: intl.get('dji.otc.om.view.field.tagName').d('BeanId'),
        required: true,
        options: BeanIdOptionsDS(optionData),
      });
      // 若该父集校验规则的值下仅有一个子值集值，则默认带出
      if (optionData.length === 1) {
        dataSet.current?.set('beanId', optionData[0].value);
      }
    });
  };

  // BeanId optionsDS
  const BeanIdOptionsDS = optionData => {
    const beanIdListOptionsDataSet = new DataSet({
      selection: 'single' as DataSetSelection,
      autoQuery: false,
      paging: false,
      data: optionData,
    });
    return beanIdListOptionsDataSet;
  };

  const openModal = type => {
    const modalDS = type === 'create' ? createListDS : tableDS;
    let title;
    if (type === 'create') {
      title = intl.get(`dji.otc.om.view.title.createOrderRule`).d('新建订单校验规则');
    } else if (type === 'edit') {
      title = intl.get(`dji.otc.om.view.title.lookOrderRule`).d('编辑订单校验规则');
    } else {
      title = intl.get(`dji.otc.om.view.title.editOrderRule`).d('查看订单校验规则');
    }
    if (type !== 'create') {
      const currentRecord = modalDS.current;
      const parentValue = currentRecord?.get('checkRuleCode');
      reqBeanIdOption(parentValue, modalDS);
    }
    if (type === 'create') {
      modalDS.create({});
    }
    Modal.open({
      key: detailModalKey,
      title: title,
      closable: true,
      drawer: true,
      children: (
        <div>
          <Form dataSet={modalDS} disabled={type === 'look'}>
            <Select name="orderTypeCodeObj" />
            <Select name="processNodeCode" />
            <Select name="checkRuleCode" />
            <Select name="beanId" />
            <NumberField name="priority" step={1} />
            <SelectBox name="controlModeCode" />
            <SelectBox name="checkRuleStatusCode" />
          </Form>
        </div>
      ),
      onCancel: () => modalDS.reset(),
      onOk: async () => {
        const validate = await modalDS.validate();
        if (validate) {
          handleOk(modalDS);
        } else {
          return false;
        }
      },
    });
  };

  const handleOk = modalDS => {
    modalDS.submit().then(
      res => {
        if (res) {
          tableDS.query();
        }
        modalDS.reset();
      },
      err => {
        console.log(err);
        modalDS.reset();
      }
    );
  };

  const Columns = useMemo<any>(
    () => [
      {
        header: intl.get(`dji.otc.om.view.field.serialNumber`).d('序号'),
        width: 50,
        lock: true,
        renderer: ({ record }) => renderSort(record, tableDS),
      },
      { name: 'orderTypeName', align: 'left', tooltip: TableColumnTooltip.always, lock: true },
      { name: 'processNodeCode', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'checkRuleCode', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'priority', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'controlModeCode', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'checkRuleStatusCode', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'createdUserName', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'creationDate', align: 'left', tooltip: TableColumnTooltip.always },
      {
        header: intl.get('dji.otc.om.view.field.operationColumn').d('操作'),
        width: 250,
        lock: ColumnLock.right,
        command: ({ record }) => {
          const checkRuleStatusCode = record.get('checkRuleStatusCode');

          return [
            <Button
              funcType={'flat' as FuncType}
              onClick={() => openModal('edit')}
            >
              <a key="edit">{intl.get(`dji.otc.om.view.button.edit`).d('编辑')}</a>
            </Button>,
            <Button
              funcType={'flat' as FuncType}
              onClick={() => openModal('look')}
            >
              <a key="look">{intl.get(`dji.otc.om.view.button.look`).d('查看')}</a>
            </Button>,
            validDom(checkRuleStatusCode, record),
            <Popconfirm
              key="confirmkey"
              title={intl.get(`dji.otc.om.view.field.confirmed_to_be_delete`).d('是否确认删除')}
              okText={intl.get(`dji.otc.om.view.field.confirm`).d('确认')}
              cancelText={intl.get(`dji.otc.om.view.field.cancel`).d('取消')}
              onConfirm={() => {
                tableDS.delete(record);
              }}
            >
              <Button funcType={'flat' as FuncType} >
                <a key="delete">{intl.get(`dji.otc.om.view.button.delete`).d('删除')}</a>
              </Button>
            </Popconfirm>,
          ];
        },
      },
    ],
    []
  );

  const validDom = (checkRuleStatusCode, record) => {
    if (checkRuleStatusCode === 'invalid') {
      return (
        <Popconfirm
          key="confirmTitle1"
          title={intl.get(`dji.otc.om.view.field.confirmed_to_be_effective`).d('是否确认生效')}
          okText={intl.get(`dji.otc.om.view.field.confirm`).d('确认')}
          cancelText={intl.get(`dji.otc.om.view.field.cancel`).d('取消')}
          onConfirm={() => {
            reqInvalid(record, 'valid');
          }}
        >
          <Button funcType={'flat' as FuncType} >
            <a key="valid">{intl.get(`dji.otc.om.view.button.invalid`).d('生效')}</a>
          </Button>
        </Popconfirm>
      );
    } else {
      return (
        <Popconfirm
          key="confirmTitle2"
          title={intl.get(`dji.otc.om.view.field.Is_failure_confirmed`).d('是否确认失效')}
          okText={intl.get(`dji.otc.om.view.field.confirm`).d('确认')}
          cancelText={intl.get(`dji.otc.om.view.field.cancel`).d('取消')}
          onConfirm={() => {
            reqInvalid(record, 'invalid');
          }}
        >
          <Button funcType={'flat' as FuncType} >
            <a key="edit">{intl.get(`dji.otc.om.view.button.invalid`).d('失效')}</a>
          </Button>
        </Popconfirm>
      );
    }
  };

  // 失效请求
  const reqInvalid = (record, type) => {
    record.set('checkRuleStatusCode', type);
    record.set('isInvalid', true);
    tableDS.submit().then(
      () => {
        tableDS.query();
      },
      () => {
        tableDS.reset();
      }
    );
  };

  // 删除选择行
  const handleDelete = () => {
    const selectdRecords = tableDS.selected;
    tableDS.delete(selectdRecords);
  };

  return (
    <div ref={pageRef}>
      <PageHeaderWrapper
        title={intl.get('dji.otc.om.view.title.orderCheckRule').d('订单校验规则')}
        header={
          <div>
            <Button onClick={() => handleDelete()}>
              {intl.get(`dji.otc.om.view.button.delete`).d('删除')}
            </Button>
            <Button color={ButtonColor.primary} onClick={() => openModal('create')}>
              {intl.get(`dji.otc.om.view.button.create`).d('新建')}
            </Button>
          </div>
        }
      >
        <Table
          dataSet={tableDS}
          // autoHeight={{ type: TableAutoHeightType.maxHeight, diff: 80 }}
          border
          columns={Columns}
          queryFieldsLimit={3}
          queryBar={props => (
            <CustomizeTableSearch
              elements={[
                <Select name="orderTypeCode" key="groupId" searchable />,
                <Select name="parentOrderTypeCode" key="groupId" searchable />,
                <Select name="checkRuleStatusCode" key="groupId" searchable />,
                <Select name="processNodeCode" key="groupId" searchable />,
                <Select name="checkRuleCode" key="groupId" searchable />,
              ]}
              // eslint-disable-next-line react/jsx-props-no-spreading
              {...props}
            />
          )}
        />
      </PageHeaderWrapper>
    </div>
  );
};

export default formatterCollections({ code: 'dji.otc.om' })(ClassPage);